package com.wing.sell.controller.admin;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.enums.ProductEnum;
import com.wing.common.enums.PurEnum;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.sell.model.entity.*;
import com.wing.sell.model.request.SelGoodsLogisticsDetailAddForm;
import com.wing.sell.model.request.SelReturnGoodRecordsUpdateForm;
import com.wing.sell.model.response.SelReturnGoodRecordsSearchVo;
import com.wing.sell.service.FinishedOrderService;
import com.wing.sell.service.OrderService;
import com.wing.sell.service.SelReturnGoodsRecordsDetailService;
import com.wing.sell.service.SelReturnGoodsRecordsService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version 1.1.0
 * @Author hz
 * @Date 2024-11-16 11:05
 **/
@Validated
@Api(value = "Admin-销售-退货记录", tags = "#/sell/returnRecords/returnRecords")
@RestController("selReturnRecordGoodController")
@RequestMapping("sell/admin/returnGoodsRecords")
@RequiredArgsConstructor
@Slf4j
public class SelReturnRecordGoodController {

    private final SelReturnGoodsRecordsService selReturnGoodsRecordsService;
    private final SelReturnGoodsRecordsDetailService selReturnGoodsRecordsDetailService;
    private final OrderService orderService;
    private final FinishedOrderService finishedOrderService;

    @ApiOperation(value = "查询所有销售退货记录", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "name", value = "名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<SelReturnGoodRecordsSearchVo> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,String type
            ,String supplierId
            ,String code
            ,String orderCode
            ,String startTime
            ,String endTime
    ){

        Page<SelReturnGoodRecordsSearchVo> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();
        params.put("type",type);
        params.put("supplierId",supplierId);
        params.put("code",code);
        params.put("orderCode",orderCode);
        params.put("startTime",startTime);
        params.put("endTime",endTime);

        Page<SelReturnGoodRecordsSearchVo> list = selReturnGoodsRecordsService.pageList4app(pg, params);
        list.getRecords().forEach(info->{
            QueryWrapper<SelReturnGoodsRecordsDetail> details = new QueryWrapper<>();
            details.eq("record_id",info.getId());
            List<SelReturnGoodsRecordsDetail> recordDt = selReturnGoodsRecordsDetailService.list(details);
            if (CollectionUtils.isNotEmpty(recordDt)){
                BigDecimal sum = recordDt.stream()
                        .filter(transaction -> transaction.getTotalPrice() != null && transaction.getTotalPrice().compareTo(BigDecimal.ZERO) > 0)  // 只累加金额大于 0 的交易
                        .map(SelReturnGoodsRecordsDetail::getTotalPrice)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                info.setTotalMoney(sum);
            }
            //设置订单编号
            if (StrUtil.isNotEmpty(info.getTypeCode())){
                //1.成品出库
                if (info.getTypeCode().equals(ProductEnum.outTypeEmum.CPC.getCode())){
                    FinishedOrder orderServiceById = finishedOrderService.getById(info.getOrderId());
                    if (orderServiceById!=null){
                        info.setOrderCode(orderServiceById.getSelCode());
                    }
                }
                //2.生产出库
                else if(info.getTypeCode().equals(ProductEnum.outTypeEmum.SCDC.getCode())){
                    Order byId = orderService.getById(info.getOrderId());
                    if (byId!=null){
                        info.setOrderCode(byId.getCode());
                    }
                }
            }

            info.setStatusName(PurEnum.returnGoodStatus.getNameByCode(info.getStatus()));
        });
        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    @ApiOperation(value = "添加退货记录", notes = "添加-退货记录")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@RequestBody SelReturnGoodRecordsUpdateForm selReturnGoodRecordsUpdateForm) {
        if (CollectionUtils.isEmpty(selReturnGoodRecordsUpdateForm.getSelReturnGoodsRecordsDetails())){
            return JsonResult.fail("未配置物料信息！");
        }
        if (selReturnGoodsRecordsService.addReturnRecordsGoods(selReturnGoodRecordsUpdateForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }

    /**
     * 换货收货
     * @param selBarterGoodRecordsUpdateForm
     * @return
     */
    @ApiOperation(value = "退货收货", notes = "退货收货")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/addLogisticsInfo")
    public JsonResult addLogisticsInfo(@RequestBody SelGoodsLogisticsDetailAddForm selBarterGoodRecordsUpdateForm) {
        if (selReturnGoodsRecordsService.addLogisticsInfo(selBarterGoodRecordsUpdateForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }

    @ApiOperation(value = "修改退货记录", notes = "修改-退货记录")
    @PutMapping("/update")
    public JsonResult update(@RequestBody SelReturnGoodRecordsUpdateForm form) {
        SelReturnGoodsRecords byId = selReturnGoodsRecordsService.getById(form.getId());
        if (ObjectUtil.isEmpty(byId)){
            return JsonResult.fail("未查询到记录");
        }
        if (selReturnGoodsRecordsService.updateReturnRecordsGoods(form) > 0) {
            return JsonResult.success("修改成功");
        }
        return JsonResult.fail("修改失败");
    }

    @ApiOperation(value = "退货记录详情", notes = "销售退货-详情")
    @GetMapping("/detail/{recordId}")
    public JsonResult update(@PathVariable("recordId") String recordId) {
        SelReturnGoodRecordsUpdateForm form =selReturnGoodsRecordsService.getByDetailId(recordId);
        if (ObjectUtil.isEmpty(form)){
            return JsonResult.fail("未查询到数据！");
        }else{
            return JsonResult.success(form);
        }
    }

    @ApiOperation(value = "退货记录财务审核", notes = "销售退货-审核")
    @PostMapping("/audit/{recordId}")
    public JsonResult audit(@PathVariable("recordId") String recordId) {
        SelReturnGoodsRecords byId = selReturnGoodsRecordsService.getById(recordId);
        if (ObjectUtil.isEmpty(byId)){
            return JsonResult.fail("未查询到数据！");
        }
        byId.setStatus(PurEnum.returnGoodStatus.DQS.getCode());
        byId.setUpdateTime(LocalDateTime.now());
        byId.setModifier(JwtUtils.getLoginUserId());
        byId.setModifierName(JwtUtils.getLoginUsername());
        boolean b = selReturnGoodsRecordsService.updateById(byId);
        if (!b){
            return JsonResult.fail("审核失败！");
        }
        return JsonResult.success("审核成功！");
    }


    @ApiOperation(value = "删除记录财务审核", notes = "删除-记录")
    @DeleteMapping("/delete/{recordId}")
    public JsonResult delete(@PathVariable("recordId") String recordId) {
        boolean b = selReturnGoodsRecordsService.deleteBy(recordId);
        if (!b){
            return JsonResult.fail("删除失败！");
        }
        return JsonResult.success("删除成功！");
    }

    @ApiOperation(value = "完结-退换货", notes = "完结")
    @PutMapping("/over/{recordId}")
    public JsonResult over(@PathVariable("recordId") String recordId) {
        SelReturnGoodsRecords byId = selReturnGoodsRecordsService.getById(recordId);
        byId.setStatus(PurEnum.returnGoodStatus.WC.getCode());
        byId.setModifier(JwtUtils.getLoginUserId());
        byId.setModifierName(JwtUtils.getLoginUsername());
        byId.setUpdateTime(LocalDateTime.now());
        boolean b = selReturnGoodsRecordsService.updateById(byId);
        if (!b){
            return JsonResult.fail("操作失败！");
        }
        return JsonResult.success("操作成功！");
    }
}
